package com.martian.service.impl;

import com.martian.common.util.Md5Util;
import com.martian.mapper.DataLoaderMapper;
import com.martian.mapper.MovieMapper;
import com.martian.mapper.RatingMapper;
import com.martian.mapper.UserMapper;
import com.martian.pojo.entity.MovieRating;
import com.martian.service.DataLoaderService;
import org.apache.catalina.LifecycleState;
//import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author martian
 * @version V1.0.0
 * @Description
 * @date 2023-03-20 9:06
 */

@Service
public class DataLoaderServiceImpl implements DataLoaderService {
    @Resource
    private DataLoaderMapper dataLoaderMapper;

    @Resource
    private RatingMapper ratingMapper;

    @Resource
    private MovieMapper movieMapper;

    @Transactional
    @Override
    public void loadMovieData() throws FileNotFoundException {
        boolean skipFirstLine = true;
        Scanner sc = new Scanner(new File("D:/SparrowRecSys-master/target/classes/webroot/sampledata/movies.csv"));
        while (sc.hasNextLine()) {
            String movieRawInfo = sc.nextLine();
            if (skipFirstLine) {
                skipFirstLine = false;
                continue;
            }
            int firstSplitIndex = movieRawInfo.indexOf(",");
            int lastSplitIndex = movieRawInfo.lastIndexOf(",");

            int movieId = Integer.parseInt(movieRawInfo.substring(0, firstSplitIndex));
            String movieNameWithYear = movieRawInfo.substring(firstSplitIndex + 1, lastSplitIndex);
            String movieGenres = movieRawInfo.substring(lastSplitIndex + 1, movieRawInfo.length());
            //提取电影发布年份
            Pattern comp = Pattern.compile("\\(([0-9}]*)\\)");
            Matcher mat = comp.matcher(movieNameWithYear);
            String movieReleasedYear = " ";
            while (mat.find()) {
                movieReleasedYear = mat.group(1);
            }
            //电影名称格式不规整，需要处理
            String movieName = movieRawInfo.substring(firstSplitIndex + 1, lastSplitIndex - 7);
            if (movieName.charAt(0) == '\"') {
                movieName = movieName.substring(1, movieName.length());
                if (movieName.contains("(")) {
                    int lastSplit3 = movieName.indexOf("(");
                    movieName = movieName.substring(0, lastSplit3);
                    if (movieName.contains(",")) {
                        int lastSplit5 = movieName.lastIndexOf(",");
                        String article = movieName.substring(lastSplit5 + 2, movieName.length() - 1);
//                        System.out.println(article);
                        if (article.equals("A") || article.equals("An") || article.equals("The")) {
                            movieName = article + movieName.substring(0, lastSplit5);
                        }
                    }
                } else {
                    if (movieName.contains(",")) {
                        int lastSplit4 = movieName.indexOf(",");
                        // 冠词 A\An\The
                        String article = movieName.substring(lastSplit4 + 2, movieName.length());
                        movieName = movieName.substring(0, lastSplit4);
                        movieName = article + movieName;
                    }
                }
                System.out.println(movieName);
                // No.1  只有逗号 39 Steps, The
//                              Old Lady Who Walked in the Sea, The (Vieille qui marchait dans la mer, La)
//                              I, the Worst of All (Yo, la peor de todas)
                // No.2  Day the Sun Turned Cold, The (Tianguo niezi)  取最后一个逗号和第一个(之间的
                // No.2  Yes, Madam (a.k.a. Police Assassins) (a.k.a. In the Line of Duty 2) (Huang gu shi jie)
//                "Day the Sun Turned Cold, The (Tianguo niezi) (1994)"
            }
            dataLoaderMapper.insertMovieData(movieId, movieName, movieGenres, movieReleasedYear, " ");
        }
    }

    @Override
    public void loadUserRating() throws FileNotFoundException, ParseException {
        boolean skipFirstLine = true;
        Scanner sc = new Scanner(new File("D:/SparrowRecSys-master/src/main/resources/webroot/sampledata/ratingSamples.csv"));
        int i = 0;
        while (sc.hasNextLine()) {
            i=i+1;
            String movieRawInfo = sc.nextLine(); // 以,分割各列元素
            if (skipFirstLine) {
                skipFirstLine = false;
                continue;
            }
            if(i < 96076){
                continue;
            }
            int userId = Integer.parseInt(movieRawInfo.split(",")[1]);
            int movieId = Integer.parseInt(movieRawInfo.split(",")[0]);
            float rating = Float.parseFloat(movieRawInfo.split(",")[2]);
            String time = movieRawInfo.split(",")[3];
            Long d = Long.valueOf(time+"000");
            Date date = new Date(d);
            SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
            dataLoaderMapper.insertRatingData(userId,movieId,rating,date);
//            System.out.println(userId+" "+movieId+" "+rating+" "+ft.format(date));
//            break;

        }
    }

    @Override
    public void loadUserInfo(){
        String[] headArr = new String[]{"user_id", "user_name", "user_password","user_salt","user_is_origin","user_is_alive"};
        //@TODO 修改绝对路径
        String filePath = "src/main/resources/data/user.csv";
        File csvFile = null;
        BufferedWriter csvWriter = null;
        try{
            csvFile = new File(filePath);
            csvFile.createNewFile();
            // GB2312使正确读取分隔符","
            csvWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);
            // 写入文件头部标题行
            csvWriter.write(String.join(",", headArr));
            csvWriter.newLine();
            // 写入文件内容
            List<Integer> userIds = ratingMapper.getDistinctUserIds();
            for (Integer userId : userIds) {
                String salt = Md5Util.salt();
                String userPassword = Md5Util.MD5Encode("123456abc"+salt);
                String userName = "root" + userId;
                csvWriter.write(userId+","+userName+","+userPassword+","+salt+",1,1");
                csvWriter.newLine();
            }
            csvWriter.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                csvWriter.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void loadMovieRating(){
        dataLoaderMapper.loadMovieAvgRating();
    }


    public static void main(String[] args) throws FileNotFoundException, ParseException {
        DataLoaderServiceImpl d = new DataLoaderServiceImpl();
        d.loadUserInfo();
//        long time=System.currentTimeMillis();
//        System.out.println(time);
//        1112484819
//        1679451282188
    }

}


